﻿#include <QtCore>

namespace helper {

void ReplaceEmojiMsgToImage(QString& source) {
  //处理emoji表情
  // source.replace(QChar(0xe412),"\xf0\x9f\x98\x82");//😂

  //映射到map文件，方便快速处理
  static QMap<QChar, QString> emojiMap;
  static QString emojiFmt = "<img class=\"message-emoji\" draggable=\"false\" src=\"emoji/%1\" />";
  if (emojiMap.isEmpty()) {
    QFile emojiFile(":/wechat/output/emoji/emoji.txt");
    emojiFile.open(QFile::ReadOnly);
    auto&& lines = emojiFile.readAll().split('\n');
    for (auto& line : lines) {
      if (line.startsWith("#")) {
        continue;
      }
      if (line.endsWith('\r')) {
        line.chop(1);
      }
      //以16进制读取存入
      QString name = line.split('.').first();
      emojiMap.insert(name.toUInt(nullptr, 16), emojiFmt.arg(line.data()));
    }
  }

  for (auto i = emojiMap.constBegin(); i != emojiMap.constEnd(); ++i) {
    source.replace(i.key(), i.value());
  }

  ///////////////////////////////////////////////////////////
  //处理QQ表情
  static QMap<QString, QString> qqMap;
  static QMap<QString, QString> qqTranslateMap;
  static QString                kTranslateFmt = "[%1]";
  static QString qqFmt = "<img class=\"message-emoji\" draggable=\"false\" src=\"qq/%1\" />";
  if (qqMap.isEmpty()) {
    QFile qqFile(":/wechat/output/qq/qq.txt");
    qqFile.open(QFile::ReadOnly);
    auto&& lines = qqFile.readAll().split('\n');
    for (auto& line : lines) {
      if (line.startsWith("#")) {
        continue;
      }
      if (line.endsWith('\r')) {
        line.chop(1);
      }

      if (line.contains('.')) {
        QString name = line.split('.').first();
        qqMap.insert(name, qqFmt.arg(line.data()));
      } else if (line.contains('=')) {
        auto&& names = line.split('=');
        qqTranslateMap.insert(QString(names[0]), QString(names[1]));
      }
    }
  }

  for (auto i = qqTranslateMap.constBegin(); i != qqTranslateMap.constEnd(); ++i) {
    source.replace("/" + i.key(), kTranslateFmt.arg(i.value()));
    source.replace(kTranslateFmt.arg(i.key()), kTranslateFmt.arg(i.value()));
  }
  for (auto i = qqMap.constBegin(); i != qqMap.constEnd(); ++i) {
    source.replace("/" + i.key(), i.value());
    source.replace(kTranslateFmt.arg(i.key()), i.value());
  }

  //处理换行符
  source.replace("\n", "<br />");
}

}  // namespace helper
